/**
 * Copyright (c) 2018, Alex. All rights reserved.
 */
package com.oschina.bottle.utils;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.springframework.beans.BeanUtils;
import org.springframework.cglib.beans.BeanMap;

/**
 * bean与map转换的工具类
 *
 * @author <a href="mailto:zhongchao@gegejia.com">zhong</a>
 * @version 1.0 2018/1/20
 * @since 1.0
 */
public class BeanMapUtils {


    /**
     * java对象转map
     *
     * @param data      待转换的数据
     * @return          map
     */
    public static <T> Map<String, Object> parseMap(T data) {
        if(data == null)
        {
            return Collections.emptyMap();
        }

        BeanMap beanMap = BeanMap.create(data);
        Map<String, Object> map = new HashMap<>(beanMap.keySet().size());
        for (Object key : beanMap.keySet()) {
            map.put(key.toString(), beanMap.get(key));
        }
        return map;
    }

    /**
     * java对象转map
     *
     * @param datas     待转换的数据
     * @return          List<Map<String, Object>>
     */
    public static <T> List<Map<String, Object>> parseMap(List<T> datas) {
        if(datas == null) {
            return Collections.emptyList();
        }

        return datas.stream().map(BeanMapUtils::parseMap).collect(Collectors.toList());
    }

    /**
     * map转java对象
     *
     * @param data      待转换的数据
     * @param clazz     java类
     * @param <T>       泛型
     * @return          泛型类
     */
    public static <T> T parseBean(Map<String, Object> data, Class<T> clazz) {
        T target = BeanUtils.instantiateClass(clazz);
        BeanMap beanMap = BeanMap.create(target);
        beanMap.putAll(data);
        return target;
    }

    /**
     * map转java对象
     *
     * @param datas     待转换的数据
     * @param clazz     java类
     * @param <T>       泛型
     * @return          泛型类
     */
    public static <T> List<T> parseBean(List<Map<String, Object>> datas, Class<T> clazz) {
        return datas.stream().map(e -> parseBean(e, clazz)).collect(Collectors.toList());
    }
}
